﻿using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using 纸片人.AttributeUsageFloder;
using 纸片人.InfoDataFolder;
using 纸片人.Shaders;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace 纸片人.PageViews
{

    [LastModified("2022-5-12", "create LiquefactionShaderTestPage.xaml")]
    [PageType("gpu", "液化（失败品）")]
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class LiquefactionShaderTestPage : Page
    {
        byte[] mappingCode;
        byte[] liqueCode;
        byte[] samplingCode;
        byte[] areaCode;
        byte[] areaSamplingCode;


        /// <summary>
        /// 映射图像
        /// </summary>
        CanvasRenderTarget mappingBitmap;

        /// <summary>
        /// 渲染后的图像
        /// </summary>
        CanvasRenderTarget renderTarget;
        CanvasRenderTarget areaRender;
        CanvasRenderTarget areaSamplingRender;

        float size = 50;
        Vector2 startPos;
        Vector2 endPos;
        public LiquefactionShaderTestPage()
        {
            this.InitializeComponent();
            LoadResource();
        }

        LayerBitmapData bitmapData = new LayerBitmapData();

        private async void LoadResource()
        {
            mappingCode = await ShaderType.LiquefactionMapping.LoadAsync();
            liqueCode = await ShaderType.Liquefaction.LoadAsync();
            samplingCode = await ShaderType.LiquefactionSampling.LoadAsync();
            areaCode = await ShaderType.LiqueArea.LoadAsync();
            areaSamplingCode = await ShaderType.AreaSampling.LoadAsync();

            //选择图片
            selectButton.Click += async (s, e) =>
            {
                await bitmapData.SelectOneBitmapAsync();
                if (bitmapData.oneBitmap == null)
                    return;
                CreateMappingBitmap();

                canvas.Invalidate();
            };


            //指针进入画布
            canvas.PointerEntered += (s, e) =>
            {

            };
            //指针离开画布
            canvas.PointerExited += (s, e) =>
            {

            };
            //指针移动
            canvas.PointerMoved += (s, e) =>
            {
                canvas.Invalidate();
            };

            canvas.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
            //拖拽开始
            canvas.ManipulationStarted += (s, e) =>
            {
                startPos = e.Position.ToVector2();
            };
            //拖拽中
            canvas.ManipulationDelta += (s, e) =>
            {
                endPos = e.Position.ToVector2();
                DrawLiqe();
                DrawArea();
                AreaSampling();
                canvas.Invalidate();
                startPos = endPos;
            };
            //绘制
            canvas.Draw += (s, e) =>
            {
                Function.DrawGridGraphics(e.DrawingSession);

               

                if (bitmapData != null && mappingBitmap != null)
                {
                    PixelShaderEffect effect = new PixelShaderEffect(samplingCode)
                    {
                        Source1 = bitmapData.oneBitmap,
                        Source2 = mappingBitmap,
                        Source2Interpolation = CanvasImageInterpolation.NearestNeighbor,
                    };
                    var width = (float)canvas.ActualWidth;
                    var height = (float)canvas.ActualHeight * 0.65;
                    var te = Function.CalcutateImageCenteredTransform(width, height, bitmapData.oneWidth, bitmapData.oneHeight);
                    te.Source = effect;
                    e.DrawingSession.DrawImage(te);
                }

                //绘制原图
                if (bitmapData.oneBitmap != null)
                {
                    var width = (float)canvas.ActualWidth * 0.25f;
                    var height = (float)canvas.ActualHeight * 0.3;
                    var te = Function.CalcutateImageCenteredTransform(width, height, bitmapData.oneWidth, bitmapData.oneHeight);
                    te.Source = bitmapData.oneBitmap;
                    e.DrawingSession.DrawImage(te, 0, (float)canvas.ActualHeight * 0.7f);
                }
                //绘制置换图
                if (mappingBitmap != null)
                {
                    var width = (float)canvas.ActualWidth * 0.25f;
                    var height = (float)canvas.ActualHeight * 0.3;
                    var te = Function.CalcutateImageCenteredTransform(width, height, bitmapData.oneWidth, bitmapData.oneHeight);
                    te.Source = mappingBitmap;
                    e.DrawingSession.DrawImage(te, width, (float)canvas.ActualHeight * 0.7f);
                }
            };

        }

        void CreateMappingBitmap()
        {
            if (bitmapData.oneBitmap != null)
            {
                mappingBitmap = new CanvasRenderTarget(canvas, bitmapData.oneBitmap.Size);
                PixelShaderEffect effect = new PixelShaderEffect(mappingCode) { Properties = { ["size"] = new Vector2(bitmapData.oneWidth, bitmapData.oneHeight) } };
                using (var ds = mappingBitmap.CreateDrawingSession())
                {
                    ds.DrawImage(effect);
                }
            }
        }

        void DrawLiqe()
        {
            if (liqueCode == null || mappingBitmap == null)
            {
                return;
            }

            //PixelShaderEffect pse = new PixelShaderEffect(liqueCode);
            //pse.Source1BorderMode = EffectBorderMode.Hard;
            //pse.Source1Interpolation = CanvasImageInterpolation.NearestNeighbor;
            //pse.Source1 = mappingBitmap;
            //pse.Properties["radius"] = (float)(size / 2f);
            //pse.Properties["position"] = startPos;
            //pse.Properties["targetPosition"] = endPos;
            //pse.Properties["pressure"] = (float)(0.5f);
            //var tempRenderTarget = new CanvasRenderTarget(canvas, mappingBitmap.Size);
            //using (var ds = tempRenderTarget.CreateDrawingSession())
            //{
            //    ds.DrawImage(pse);
            //}
            //mappingBitmap = tempRenderTarget;


            //PixelShaderEffect rps = new PixelShaderEffect(liqueCode)
            //{
            //    Source1BorderMode = EffectBorderMode.Hard,
            //    Source1Interpolation = CanvasImageInterpolation.NearestNeighbor,
            //    Source1 = renderTarget,
            //    Properties =
            //    {
            //     ["radius"] =(float)((size / 2f)/Math.Max(originalBitmap.Size.Width,originalBitmap.Size.Height) ),
            //        ["position"] = Vector2.Divide(startPos,originalBitmap.Size.ToVector2()),
            //        ["targetPosition"] =Vector2.Divide(endPos,originalBitmap.Size.ToVector2()) ,
            //        ["pressure"] = (float)(0.5f),
            //    }
            //};

            //var t1 = new CanvasRenderTarget(canvas, renderTarget.Size);
            //using (var ds = t1.CreateDrawingSession())
            //{
            //    ds.DrawImage(rps);
            //}
            //renderTarget = t1;



        }


        void DrawArea()
        {
            //PixelShaderEffect area = new PixelShaderEffect(areaCode)
            //{
            //    Source1 = areaRender,
            //    Properties =
            //    {
            //        ["radius"] =(float)((size / 2f)/Math.Max(originalBitmap.Size.Width,originalBitmap.Size.Height)) ,
            //        ["position"] = Vector2.Divide(startPos,originalBitmap.Size.ToVector2()),
            //        ["targetPosition"] =Vector2.Divide(endPos,originalBitmap.Size.ToVector2()) ,
            //        ["pressure"] = (float)(0.5f),
            //    }
            //};

            //var t1 = new CanvasRenderTarget(canvas, renderTarget.Size);
            //using (var ds = t1.CreateDrawingSession())
            //{
            //    ds.DrawImage(areaRender);
            //    ds.DrawImage(area);
            //}
            //areaRender = t1;
        }


        void AreaSampling()
        {
            //var pse = new PixelShaderEffect(areaSamplingCode)
            //{
            //    Source1 = renderTarget,
            //    Source2 = areaRender,
            //    Source2Interpolation = CanvasImageInterpolation.NearestNeighbor
            //};

            //using (var ds = areaSamplingRender.CreateDrawingSession())
            //{
            //    ds.Clear(Colors.Transparent);
            //    ds.DrawImage(pse);
            //}
        }


    }
}
